<script setup>
import { userRegisterService, userLoginService } from '@/api/user'
import * as schoolApi from '@/api/school'
// import { getSchoolListService } from '@/api/school'
import { User, Lock } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { useUserStore } from '@/stores/index'
import { useRouter } from 'vue-router'
import Picker from '@/components/Picker.vue'
import { getSchoolListService } from '@/api/school'
import { ElLoading, ElMessage } from 'element-plus'
const isRegister = ref(false)
const form = ref() //添加一个对象来绑定对应的表单对象 使用v-if同一时间页面只会出现一个from表单

// 整个的用于提交的form数据对象
const formModel = ref({
  username: '',
  password: '',
  repassword: '', //在此输入密码
  school: '', //学校
  name: '', //姓名
  phone: '', //手机号
})

// 定义 schoolList 响应式变量
const schoolList = ref([])
const fileschoollist = ref([])

const rules = {
  // 1. 非空校验 required: true      message消息提示，  trigger触发校验的时机 blur 失去焦点时触发 change 内容改变时触发
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 15, message: '长度在5到15个字符', trigger: 'blur' }, //长度校验
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15个数字',
      trigger: 'blur',
    }, //正则校验
  ],
  repassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15个数字',
      trigger: 'blur',
    }, //正则校验
    {
      //自定义校验规则
      validator: (rule, value, callback) => {
        //判断两次密码是否一致
        if (value !== formModel.value.password) {
          callback(new Error('两次密码不一致'))
        } else {
          callback() //校验成功也需要调用回调函数
        }
      },
    },
  ],
}

const register = async () => {
  //对整个表单进行验证  validate() 是 el-form 组件提供的方法，用于验证表单数据
  console.log(form.value)

  await form.value.validate()
  console.log('开始注册请求')
  let res = await userRegisterService(formModel.value)
  console.log(res)

  //弹窗提示跳转登录页面
  // alert("注册成功，请登录")
  // 使用elui进行弹窗提示 导入对应的数据   配置全局变量表示全局导入就不会报错
  ElMessage.success('注册成功，请登录')
  //注册成功后，跳转到登录页面
  isRegister.value = false
}

const userStore = useUserStore()
const router = useRouter()
//登录页面
const login = async () => {
  //对整个表单进行验证  validate() 是 el-form 组件提供的方法，用于验证表单数据
  // 提交之前先进行数据校验
  console.log(formModel.value)
  await form.value.validate()
  console.log('开始登录请求')
  // 等待提示
  ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  //接受成功之后的信息
  let res
  try {
    res = await userLoginService(formModel.value)
  } catch (err) {
    ElMessage.error(err.message)
    ElLoading.service().close()
    return
  }
  console.log(res)
  ElMessage.success('登陆成功')
  // 关闭等待提示
  ElLoading.service().close()
  // 将返回的token存储到本地
  userStore.seToken(res.data.token)
  userStore.setUser(res.data)
  // 跳转主页面
  router.push('/')
}

// 切换时充值表单
watch(isRegister, () => {
  formModel.value = {
    username: '',
    password: '',
    repassword: '', //在此输入密码
    school: '', //学校
    name: '', //姓名
    phone: '', //手机号
  }
})

// 自定义过滤方法
const filterSchool = (query, option) => {
  console.log('query:', query)
  console.log('option:', option)
  if (!query) {
    fileschoollist.value = schoolList.value
    return true
  }
  let a = schoolList.value.filter((item) =>
    item.schoolname.toLowerCase().includes(query),
  )
  fileschoollist.value = a
  return
}

//页面加载完成获取学校
onMounted(async () => {
  const res = await getSchoolListService()
  //获取到的学校信息
  let r = res.data.data
  //将学校信息赋值给学校列表
  schoolList.value = r
  fileschoollist.value = r
  console.log(r)
})
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册相关表单  rules 绑定对应的验证事件 ref绑定对应的vue属性from-->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isRegister"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <!--  学校输入框改成可搜索的下拉列表  -->
        <el-form-item prop="school">
          <el-select
            v-model="formModel.school"
            placeholder="请选择学校"
            :filter-method="filterSchool"
            filterable
          >
            <el-option
              v-for="item in fileschoollist"
              :key="item.id"
              :label="item.schoolname"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!--        <el-form-item prop="school">-->
        <!--          <el-select-->
        <!--            v-model="formModel.school"-->
        <!--            placeholder="请选择学校"-->
        <!--            :filter-method="filterSchool"-->
        <!--            filterable-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="item in fileschoollist"-->
        <!--              :key="item.id"-->
        <!--              :label="item.schoolname"-->
        <!--              :value="item.id"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item prop="username">
          <!-- 跟数据进行双向绑定 -->
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>

        <el-form-item prop="name">
          <!-- 跟数据进行双向绑定 -->
          <el-input
            v-model="formModel.name"
            :prefix-icon="User"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <!-- 跟数据进行双向绑定 -->
          <el-input
            v-model="formModel.phone"
            :prefix-icon="User"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            v-model="formModel.repassword"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入再次密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="register"
            class="button"
            type="primary"
            auto-insert-space
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>

      <!-- 登录相关表单 -->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-else
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <!--  学校输入框改成可搜索的下拉列表  -->
        <el-form-item prop="school">
          <Picker
            @update:model-value="(value) => (formModel.school = value)"
            :fetch-list="schoolApi.fetchSchoolList"
            placeholder="请选择学校"
            label-key="schoolname"
          ></Picker>
        </el-form-item>

        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="login"
            class="button"
            type="primary"
            auto-insert-space
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background:
      url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
      url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
